/**
 * 
 */
var addPlace = false; 


$(document).ready(function() { 
	
		
	$("#addNewPlaceButton").click(function() { 
		addPlace = true;
		showToast(TOUCH_SCREEN_ADD_NEW_PLACE, TOAST_INFO); 
		$( "#right_panel" ).panel( "close" );
		//$.mobile.changePage( $('#addPlacePopup'), { role: 'dialog', transition: 'none'});  
	});  
	
	$("#addPlaceTypeList").click(function() {		 
		$.mobile.changePage( $('#placeTypePopup'), { role: 'dialog', transition: 'none'});  
	});  
	
	
	
	$("#removePlaceButton").click(function() {		
		console.log("SHOW remove place.");
		
		$('#removeHeader h1:first').text($("#markerTittle label:first").text());
		 //Si pongo pop entonces tengo el error de que la pantalla no se centra. solo pasa en iOS
		$.mobile.changePage( $('#removePopup'), { role: 'dialog', transition: 'none'});  
	});
	
	$("#sendRemovePlaceButton").click(function(event) {		
		
		console.log("SHOW remove place."+$('#removeReasonTextarea').val().length);
		if($('#removeReasonTextarea').val().length < REASON_MIN_LENGTH){
			showToast(RESON_MIN_LENGTH_TEXT, TOAST_ERROR);
			//TODO enviarnos un email a nosotros.
		}else{
			var remove = {
					"placeId" : viewedPlace.id,
					"reason" : $("#removeReasonTextarea").val()
				};
			removePlaceComments(remove);             	
		}
	}); 
	
	$("#showCommentButton").click(function(event) {		
		if(typeof viewedPlace == 'undefined' ){
			showToast(jQuery.i18n.prop('errorAlObtenerPosicionActual'), TOAST_ERROR);
			//TODO enviarnos un email a nosotros.
		}else{
			
			getPlaceComments();             	
		}
	}); 
	
	
	$("#getDirectionsButton").click(function(event) {		
		if(typeof viewedPlace == 'undefined' ){
			showToast(jQuery.i18n.prop('errorAlObtenerPosicionActual'), TOAST_ERROR);
			//TODO enviarnos un email a nosotros.
		}else{
			getCurrentPosition(showDirections);	             	
		}
	}); 
	
	$('#disclaimerLink').bind('click tap',function( event, data ){
		  //  event.stopPropagation();
		    console.log("saleeee dis claimerLink");
		   // $.mobile.changePage($('#popupInfo'), { role: 'popup', transition: 'none'});
		    
		    $('#popupInfo').popup('open');
		});
	
	
	$("#ratePlaceButton").click(function() { 
		// rate
		$('#ratePlace').raty({ score : 3 }); 
		
		console.log($("#markerTittle label:first").text());
		
		$('#rateHeader h1:first').text($("#markerTittle label:first").text());
		 //Si pongo pop entonces tengo el error de que la pantalla no se centra. solo pasa en iOS
		$.mobile.changePage( $('#ratePopup'), { role: 'dialog', transition: 'none'});  
	});
	
	$("#sendRateButton").click(function() { 
		if($('#rateCommentTextarea').val().length > 0){
			if($("#disclaimerCB").is(':checked')){
				var valores = {
						"id" : viewedPlace.id,
						"comment" : $("#rateCommentTextarea").val(),
						"rate" : $('#rateTittle div:first').raty('score')
					};
				$('#ratePopup').dialog('close');
				sendRating(valores);	
			}else{
				showToast(CONFIRM_18_OLDER, TOAST_ERROR);				
			}
		}else{			 
			showToast(COMMENT_MANDATORY, TOAST_ERROR);
		} 
	});
}); 


function showToast(texto,tipo){
	$().toastmessage('showToast', {
	    text     : texto,
	    sticky   : false, //se cierra automaticamented
	    position : 'middle-center',
	    stayTime : 5000,
	    type     : tipo
	});
}



function showCustomDialog(marker, place) {
	console.log("Mapa : showCustomDialog : mostramos el dialgo.");
	
	viewedPlace = place; 
	$('#markerHeader h1:first').text(marker.getTitle());

	// tittle
	$("#markerImage").attr("src", marker.getIcon());
	$("#markerTittle label:first").text(marker.getTitle());
	//rate	
	$('#star').raty({
		readOnly : true,
		score : place.rate
	});
	 
	//distance   
	var distancia = google.maps.geometry.spherical.computeDistanceBetween (yourPosition, marker.getPosition());
 
	//TODO cuando sea muy grande mostrar KM
	$("#markerDistance label:nth-child(2)").text(Math.round(distancia/1000).toFixed(2)+' Km');
	
	//Comment
	$("#markerComment label:nth-child(2)").text(place.description);
	  
	$.mobile.changePage( $('#markerPopup'), { role: 'dialog', transition: 'none'});  
}

function showDirections(position){
	var url = GET_DIRECTIONS+
		"daddr="+viewedPlace.latitude+","+viewedPlace.longitude+
		"&saddr="+position.coords.latitude+","+position.coords.longitude; 
	
	window.open(url, "_blank","", true);	
}


function showPlaceComments(data) {
	console.log("View : showPlaceComments : mostramos los comentarios.");
	console.log("View : showPlaceComments : data "+data);
	 
	$('#commentHeader h1:first').text(COMMENTS.toUpperCase()+" - "+viewedPlace.name);

	//comment	"gdhkkj"	id	2663 rate	3.5 registerDate	"2013-11-30"
	
	/*
	 <li><a href="#">
     <img src="../static/images/album-p.jpg">
	    <h2>Broken Bells</h2>
	    <p>Broken Bells</p>
 </a>
</li>
*/
	var html="";
	//Create listview without Rate Score.
	var estilo = 'style="font-weight: lighter;"';
	 $.each(data, function(index, item) {
         html += 
        	 '<li><a href="#" class="rateListView">' +
        	 	'<img src="../static/images/default_user.png" style="padding:3%;">'+
        	 	' <label for="itemComment" >'+item.comment+'.</label><br>'+
        	 	//TODO agregar nombre usuario
        	 	' <label for="itemWrittenBy" '+estilo+'>'+USER+'&nbsp&nbsp</label></br>'+
        	 	'<div id="rate'+item.id+'"> <label for="itemRate"'+estilo+' >'+RATE+'&nbsp&nbsp&nbsp</label></div>'+
        	 	' <label for="itemDate" '+estilo+'>'+DATE+'&nbsp&nbsp</label>'+item.registerDate+'</br>'+
        	 	'</a></li>';
     });
	 $("#commentList").append(html);
		
	//After listview creation and append to Dom we can give rate score.
	 $.each(data, function(index, item) {		 
		 $('#rate'+item.id).raty({
				readOnly : true,
				score : item.rate
			});
     });
	$.mobile.changePage( $('#commentPopup'), { role: 'dialog', transition: 'none'});  

}
 
function selectPlaceTypeSelected(id,name, imgPath){
	$('#placeTypePopup').dialog('close');
		
	var type = '<li><a href="#" ><img class="ui-li-icon" src="'+imgPath+'">'+name+'</a></li>';
	$('#addPlaceTypeList').html(type);
	$('#addPlaceTypeList').listview( "refresh" );
	console.log("icno selected "+name);
}

function showAddPlaceDialog(latitud, longitud) {
	if(addPlace){
		// rate
		$('#addPlaceRate').raty({ score : 3 }); 
		
		$.mobile.changePage( $('#addPlacePopup'), { role: 'dialog', transition: 'none'});  
		addPlace = false;
	}	
	
}